package com.xpc.proxy.common;



import com.xpc.proxy.common.consumer.Consumer;
import com.xpc.rpc.common.enums.RpcMsgType;
import com.xpc.rpc.protocol.ProtocolMessage;
import com.xpc.rpc.protocol.header.RpcHeader;
import com.xpc.rpc.protocol.request.RpcRequest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class ObjectProxy <T> implements InvocationHandler {


    private Consumer consumer;

    private Class<T> clazz;

    private int serializationType;

    public ObjectProxy(Consumer consumer,Class clazz,int serializationType) {
        this.consumer = consumer;
        this.clazz = clazz;
        this.serializationType = serializationType;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        ProtocolMessage<RpcRequest> rpcRequestProtocolMessage = new ProtocolMessage<>();
        RpcRequest rpcRequest = new RpcRequest();
        RpcHeader rpcHeader = new RpcHeader();
        rpcHeader.setMsgType(RpcMsgType.REQUEST.getType());
        rpcHeader.setRequestId(1L);
        rpcHeader.setSerializationType(serializationType);
        rpcRequestProtocolMessage.setRpcHeader(rpcHeader);
        rpcRequest.setClassName(clazz.getName());
        rpcRequest.setMethodName(method.getName());
        rpcRequest.setParameterTypes(method.getParameterTypes());
        rpcRequest.setParameters(args);
        rpcRequestProtocolMessage.setT(rpcRequest);
        return consumer.sendRequest(rpcRequestProtocolMessage);
    }
}
